package com.young.fragments.demo.activity_result_launcher_demo

import android.app.Activity
import android.content.Intent
import android.os.Bundle
import android.view.KeyEvent
import androidx.fragment.app.FragmentActivity
import com.young.fragments.databinding.ActivityResultDoBackBinding

/**
 * @author huangzehui
 * @date 2025/1/26 22:33 周日
 * @description registerForActivityResult 返回结果activity
 */
class ResultDoBackActivity : FragmentActivity() {

    companion object {
        // key - 返回的数据信息
        const val KEY_BACK_DATA = "back_data"
    }

    private val mBinding by lazy {
        ActivityResultDoBackBinding.inflate(layoutInflater)
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(mBinding.root)

        initClick()
    }

    override fun onKeyDown(keyCode: Int, event: KeyEvent?): Boolean {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            back()
        }
        return super.onKeyDown(keyCode, event)
    }

    private fun initClick() {
        mBinding.btnSend.setOnClickListener {
            send()
        }
    }

    /**
     * 发送，将数据返回上个页面
     */
    private fun send() {
        val data = Intent()
        var text = mBinding.etText.text.toString().replace(" ", "")
        if (text.isEmpty()) {
            text = "输入的内容是空的"
        }
        data.putExtra(KEY_BACK_DATA, text)

        val resultCode =
            intent.getIntExtra(ActivityResultLauncherActivity.KEY_RESULT_CODE, Activity.RESULT_OK)
        setResult(resultCode, data)

        finish()
    }

    /**
     * 返回
     */
    private fun back() {
        val data = Intent()
        data.putExtra(KEY_BACK_DATA, "按了返回键")

        val resultCode =
            intent.getIntExtra(ActivityResultLauncherActivity.KEY_RESULT_CODE, Activity.RESULT_OK)
        setResult(resultCode, data)

    }

}